package com.thank.concurrency.samples.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 演示CyclicBarrier的await方法和Runnable方法
 */
@Slf4j
public class CyclicBarrierExample2 {

    // 指定有x个线程同步等待,  当线程全部到达屏障时，优先执行这里的Runnable方法
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () ->
        log.info("Runnable callback is running")
    );

    public static void main(String[] args) throws Exception {
        ExecutorService exec = Executors.newCachedThreadPool();

        for (int i = 0; i < 4; i++) {
            final int threadNum = i;
            // 延迟1秒, 方便观察
            Thread.sleep(1000);
            exec.execute(() -> {
                try {
                    race(threadNum);
                } catch (Exception e) {
                    log.error("exception", e);
                }
            });
        }

        exec.shutdown();
    }

    private static void race(int threadNum) throws Exception {
        Thread.sleep(1000);
        log.info("{} is ready", threadNum);
        // 使用await方法进行等待(x个线程互相等待)
        cyclicBarrier.await();
        log.info("{} is continue", threadNum);
    }
}
